package xiaopiya.robot.handler.rss;

import org.apache.commons.lang.StringUtils;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

import xiaopiya.robot.handler.main.MainMessageHandler;
import xiaopiya.robot.handler.rss.exception.RssContentException;
import xiaopiya.robot.handler.rss.tool.RssChannelManager;
import xiaopiya.robot.handler.rss.tool.RssContent;

/**
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class RssMessageHandler extends MainMessageHandler
{
	private RssChannelManager rssChannelManager;

	public void setRssChannelManager(RssChannelManager rssChannelManager)
	{
		this.rssChannelManager = rssChannelManager;
	}

	public void handle(XMPPConnection connection, Chat chat, Message message,
			String body) throws XMPPException
	{
		body = body.trim();
		if (body.startsWith("-c"))
		{
			body = body.substring("-c".length(), body.length());
		}

		body = body.trim();
		if (body.length() == 0)
		{
			body = getDefaultHandleCommand();
		}

		if (body.length() > 0)
		{
			body = ":" + body;
		}
		super.handle(connection, chat, message, body);
	}

	protected String getCommandError(String command, String messageBody)
	{
		messageBody = messageBody.trim();
		if (StringUtils.isEmpty(messageBody))
		{
			return "请指定RSS子频道";
		}
		try
		{
			RssContent rssContent = this.rssChannelManager
					.getLastGet(new ChannelKey(command, messageBody));
			if (rssContent == null)
			{
				return "RSS频道" + command + " " + messageBody + "不存在";
			} else
			{
				return rssContent.toString();
			}
		} catch (RssContentException e)
		{
			return "获取RSS频道" + command + " " + messageBody + "失败";
		}
	}
}